package cn.jbooter.shiro.autoconfigure.filter.spring_session.authc;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jbooter.shiro.autoconfigure.util.ShiroUtil;


/**
 * spring-session的rest接口的退出拦截器
 * @author hejian
 *
 */
public class SSRestLogoutFilter extends AdviceFilter {
	private static final Logger logger = LoggerFactory.getLogger(SSRestLogoutFilter.class);
	
	
	@Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        try {
        	Object principal = subject.getPrincipal();
            subject.logout();
            logger.info("用户:"+principal+" 退出登陆成功!");
        } catch (SessionException ise) {
            logger.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
        }
        //向客户端写退出成功
        ShiroUtil.writeSuccess("退出登陆成功!", (HttpServletResponse)response);
        return false;
    }
	
	protected Subject getSubject(ServletRequest request, ServletResponse response) {
        return SecurityUtils.getSubject();
    }
	
}
